﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace ZhuXingFamilys.test
{
    [Transaction(TransactionMode.Manual)]
    class FamilyFileConvert_1 : IExternalCommand
    {
        public string Categroyname ;
        public string Unit ;
        public string Familynumber ;
        public  string Projectname;
        public string Projectfeatures;
        public int Length ;
        public int Height ;
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            try
            {
                FamilyFileCopyFrom form1 = new FamilyFileCopyFrom();
                form1.ShowDialog();

                UIApplication uiApp = commandData.Application;
                Autodesk.Revit.ApplicationServices.Application app = uiApp.Application;
                string address = FamilyFileCopyFrom.Getpathaddress1();
                //@"C:\Users\Administrator\Desktop\1.xlsx";
                string rfapath = FamilyFileCopyFrom.Getpathrfapath1();
                //@"D:\基础梁-120x200-C20.rfa";
                string filename = Path.GetFileNameWithoutExtension(rfapath);
                string  savepath= FamilyFileCopyFrom.Getsavepath();
                if (address != null && filename != null && savepath != null)
                {


                    DataTable dt = ExcelToDS(address);

                    foreach (DataRow items in dt.Rows)
                    {
                        Document newDoc = app.OpenDocumentFile(rfapath);
                        FamilyManager familyManager = newDoc.FamilyManager;
                        Categroyname = items[0].ToString();
                        Unit = items[1].ToString().Replace("m3", "m\xB3").Replace("m2", "m\xB2");
                        Familynumber = items[2].ToString();
                        Projectname = items[3].ToString();
                        Projectfeatures = items[4].ToString();
                        Length = int.Parse(items[5].ToString());
                        Height = int.Parse(items[6].ToString());

                        if (newDoc != null)
                        {
                            //切换族类型
                            using (Transaction trans = new Transaction(newDoc, "changeType"))
                            {
                                trans.Start();
                                foreach (FamilyType familyType in familyManager.Types)
                                {
                                    if (familyType.Name == filename)
                                    {
                                        familyManager.CurrentType = familyType;
                                        newDoc.FamilyManager.RenameCurrentType(Categroyname);
                                    }
                                }
                                trans.Commit();
                            }

                            using (Transaction trans = new Transaction(newDoc))
                            {
                                trans.Start("Update Parameter");
                                //FamilyParameter fParametercn = familyManager.get_Parameter("类型名称");
                                //familyManager.Set(fParametercn, categroyname);
                                FamilyParameter fParameterfn = familyManager.get_Parameter("族库编号");
                                familyManager.Set(fParameterfn, Familynumber);
                                FamilyParameter fParameterunit = familyManager.get_Parameter("计量单位");
                                familyManager.Set(fParameterunit, Unit);
                                FamilyParameter fParameterpn = familyManager.get_Parameter("项目名称");
                                familyManager.Set(fParameterpn, Projectname);
                                FamilyParameter fParameterpf = familyManager.get_Parameter("项目特征");
                                familyManager.Set(fParameterpf, Projectfeatures);
                                FamilyParameter fParameterb = familyManager.get_Parameter("b");
                                familyManager.Set(fParameterb, Length / 304.8);
                                FamilyParameter fParameterh = familyManager.get_Parameter("h");
                                familyManager.Set(fParameterh, Height / 304.8);

                                trans.Commit();
                            }
                            SaveOptions saveOpt = new SaveOptions();
                            saveOpt.Compact = true;
                            string repath = savepath + "\\" + Categroyname + ".rfa11";
                            if (File.Exists(repath))
                            {
                                File.Delete(repath);

                            }
                            newDoc.SaveAs(repath);

                            newDoc.Close();
                        }
                    }

                }
                return Result.Succeeded;
            }
            catch (Exception exception)
            {
                message = exception.Message;
                return Result.Failed;
            }
        }
        //读取excel数据转化为datatable
        public DataTable ExcelToDS(string FileName)
        {
            //实例化DataTable来存放数据
            DataTable dt = new DataTable();
            string sheetName = "sheet1";//Excel的工作表名称
            bool isColumnName = true;//判断第一行是否为标题列
            IWorkbook workbook;//创建一个工作薄接口
            string fileExt = System.IO.Path.GetExtension(FileName).ToLower();//获取文件的拓展名
            //创建一个文件流
            using (FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read))
            {
                if (fileExt == ".xlsx")
                {
                    workbook = new XSSFWorkbook(fs);
                }
                else
                {
                    workbook = null;
                }

                //实例化sheet
                ISheet sheet = null;
                if (sheetName != null && sheetName != "")//判断是否存在sheet
                {
                    sheet = workbook.GetSheet(sheetName);
                    if (sheet == null)
                    {
                        sheet = workbook.GetSheetAt(0);//从第一个开始读取，0位索引
                    }
                    else
                    {
                        sheet = workbook.GetSheetAt(0);
                    }
                }

                //获取表头
                IRow header = sheet.GetRow(sheet.FirstRowNum);
                int startRow = 0;//数据的第一行索引
                if (isColumnName)//表示第一行是列名
                {
                    startRow = sheet.FirstRowNum + 1;//数据从第二行开始读

                    //遍历表的第一行，即所有的列名
                    for (int i = header.FirstCellNum; i < header.LastCellNum; i++)
                    {
                        ICell cell = header.GetCell(i);
                        if (cell != null)
                        {
                            //获取列名的值
                            string cellValue = cell.ToString();
                            if (cellValue != null)
                            {
                                DataColumn col = new DataColumn(cellValue);
                                dt.Columns.Add(col);
                            }
                            else
                            {
                                DataColumn col = new DataColumn();
                                dt.Columns.Add(col);
                            }
                        }
                    }
                }

                //读取数据
                for (int i = startRow; i <= sheet.LastRowNum; i++)
                {
                    IRow row = sheet.GetRow(i);
                    if (row == null)
                    {
                        continue;
                    }
                    DataRow dr = dt.NewRow();
                    for (int j = row.FirstCellNum; j < row.LastCellNum; j++)
                    {
                        if (row.GetCell(j) != null)
                        {
                            dr[j] = row.GetCell(j).ToString();
                        }

                    }
                    dt.Rows.Add(dr);
                }
                return dt;
            }
        }

    }
}
